import { fetchResource } from '../utils/fetchResource'
// import { performScriptForEval } from '../sandbox/performScript'
import { sandbox } from '../sandbox'

export const loadHtml = async (app) => {
    // 子应用显示位置
    let container = app.container
    // 子应用入口
    let entry = app.entry
    const [dom, scripts] = await parseHtml(entry, app.name)
    const ct = document.querySelector(container)
    if (!ct) {
        throw new Error(`${container} is not exist`)
    }
    ct.innerHTML = dom
    scripts.forEach(item => {
        sandbox(app, item)
    })
    return app
}
const cache = {} // 根据子应用name 缓存

export const parseHtml = async (entry, name) => {
    if (cache[name]) {
        return cache[name]
    }
    const html = await fetchResource(entry)
    const div = document.createElement('div')
    div.innerHTML = html
    // 标签 link script(src, js)
    let allScript = []
    const [dom, scriptUrl, script] = await getResources(div, entry)
    const fetchScripts = await Promise.all(scriptUrl.map(async item => fetchResource(item)))
    allScript = script.concat(fetchScripts)
    cache[name] = [dom, allScript]
    return [dom, allScript]
}

export const getResources = async (root, entry) => {
    let scriptUrl = []
    let script = []
    const dom = root.outerHTML

    function deepParse(element) {
        const children = element.children
        const parent = element.parent
        if (element.nodeName.toLowerCase() === 'script') {
            const src = element.getAttribute('src')
            if (!src) {
                script.push(element.outerHTML)
            } else {
                if (src.startsWith('http')) {
                    scriptUrl.push(src)
                } else {
                    scriptUrl.push(`http:${entry}/${src}`)
                }
            }
            if (parent) {
                parent.replaceChild(document.createTextNode('此文件已被微前端替换'), element)
            }
        }

        if (element.nodeName.toLowerCase() === 'link') {
            const href = element.getAttribute('href')
            if (href.endsWith('.js')) {
                if (href.startsWith('http')) {
                    scriptUrl.push(src)
                } else {
                    scriptUrl.push(`http:${entry}/${src}`)
                }
            }
            // 如果不是endsWith('.js')呢
        }
        for (let i = 0; i < children.length; i++) {
            deepParse(children[i])
        }
    }
    deepParse(root)
    return [dom, scriptUrl, script]
}
